package com.taoyibao.hongcanting.ui.login.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.activity.BaseActivityPresenter;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.event.EventFinishActivity;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.LoginModel;
import com.taoyibao.hongcanting.ui.MainActivity;
import com.taoyibao.hongcanting.ui.admin.activity.AdministratorActivity;
import com.taoyibao.hongcanting.ui.admin.activity.WaiterActivity;
import com.taoyibao.hongcanting.ui.login.delegate.LoginDelegate;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.JPushUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * @author TangAnna
 * @description: 登录
 * @date :${DATA} 15:39
 */
public class LoginActivity extends BaseActivityPresenter<LoginDelegate> implements View.OnClickListener {

    /**
     * 页面来源 有值时需要跳转首页 （屏幕操作员端使用） 没有值时直接关闭
     */
    private String mSource;

    @Override
    protected Class<LoginDelegate> getDelegateClass() {
        return LoginDelegate.class;
    }

    /**
     * @param context
     * @param source  页面来源  没有操作的话直接关闭页面必须要传值
     */
    public static void open(Context context, String source) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(CodeConstant.ACTIVITY_SOURCE, source);
        context.startActivity(intent);
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        mSource = getIntent().getStringExtra(CodeConstant.ACTIVITY_SOURCE);
        //清除设置的身份tag
        JPushUtils.cleanTags(JPushUtils.SEQUENCE_IDENTITY_0);
        viewDelegate.get(R.id.btn_login).setOnClickListener(this);
        viewDelegate.get(R.id.tv_login_getVCode).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login://登录
                if (viewDelegate.isCanLogin()) {
                    onLogin();
                }
                break;
            case R.id.tv_login_getVCode://发送验证码
                if (viewDelegate.isCanVCode()) {
                    getVcode();
                }
                break;
        }
    }

    /**
     * 获取验证码
     */
    public void getVcode() {
        JsonApiWrapper.getApiService().sendCode(viewDelegate.getPhone())
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel result) {
                        if (result.code == NetCode.HTTP_200) {
                            CodeUtils.setSecurityTextView((TextView) viewDelegate.get(R.id.tv_login_getVCode));
                        } else {
                            super.onNext(result);
                        }
                    }
                });
    }

    /**
     * 登录
     */
    public void onLogin() {
        JsonApiWrapper.getApiService().login(viewDelegate.getPhone(), viewDelegate.getVCodeStr())
                .compose(new DefaultTransformer<CompanyBaseModel<List<LoginModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<LoginModel>>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<List<LoginModel>> resultModel) {
                        if (resultModel.code == NetCode.HTTP_200 && resultModel.data != null && resultModel.data.size() > 0) {
                            loginSuccess(resultModel.data.get(0));
                        } else {
                            super.onNext(resultModel);
                        }
                    }
                });
    }

    /**
     * 登录成功操作
     * 保存登录状态 用户信息
     *
     * @param resultModel
     */
    public void loginSuccess(LoginModel resultModel) {
        SpUtils.putLoginStatus(true);
        SpUtils.putMemberId(resultModel.memberId);
        SpUtils.putUserPhone(viewDelegate.getPhone());
        SpUtils.putToken(resultModel.token);
        SpUtils.putUserType(resultModel.user_type);
        SpUtils.putAdminNub(resultModel.id);
        onNext(resultModel);
    }

    /**
     * 页面跳转
     * <p>
     * 根据用户的类型设置极光中用到的Tag
     *
     * @param resultModel
     */
    public void onNext(LoginModel resultModel) {
        if (SpUtils.getUserType() == CodeConstant.USER_TYPE_USER) {//普通用户
            if (resultModel.user_fresh == CodeConstant.USER_FRESH_1) {//首次注册 要跳转到设置个人信息页面
                SetPersonInfoActivity.open(this);
            } else if (!TextUtils.isEmpty(mSource)) {//屏幕操作员端
                startActivity(new Intent(this, MainActivity.class));
            }
        } else if (SpUtils.getUserType() == CodeConstant.USER_TYPE_SCREEN_OPERATOR) {//屏幕操作员
            //设置屏幕操作员的极光tag值
            JPushUtils.setTags(JPushUtils.SEQUENCE_IDENTITY_0, JPushUtils.getScreenerTag());
            sendFinishMain();
            startActivity(new Intent(this, AdministratorActivity.class));
        } else if (SpUtils.getUserType() == CodeConstant.USER_TYPE_WAITER) {//服务员
            JPushUtils.setTags(JPushUtils.SEQUENCE_IDENTITY_0, JPushUtils.getWaiterTag());
            sendFinishMain();
            startActivity(new Intent(this, WaiterActivity.class));
        }
        finish();
    }

    /**
     * 发送消息关闭首页
     */
    public void sendFinishMain() {
        EventFinishActivity event = new EventFinishActivity();
        event.mainAvtivity = true;
        EventBus.getDefault().post(event);
    }
}
